<template>
	<div class="login-container">
		<el-card class="box-card">
			<div slot="header" class="clearfix">
				<span>登录</span>
			</div>
			<el-form :model="loginForm" :rules="rules" ref="loginFormRef" label-width="100px" class="demo-ruleForm">
				<el-form-item prop="username" label="用户名">
					<el-input v-model="loginForm.username"></el-input>
				</el-form-item>
				<el-form-item prop="password" label="密码">
					<el-input v-model="loginForm.password" type="password"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="submitForm">登录</el-button>
					<el-button @click="resetForm">重置</el-button>
				</el-form-item>
			</el-form>
		</el-card>
	</div>
</template>

<script setup lang="ts">
import {reactive, ref} from "vue";
import {useRouter} from "vue-router";
import {ElMessage} from "element-plus";
import axios from "@/api";

const router = useRouter()

const loginForm = reactive({
	username: '',
	password: ''
})

const loginFormRef = ref(null)

const rules = reactive({
	username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
	password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
})

const submitForm = () => {
	(loginFormRef.value as any).validate((valid: boolean) => {
		if (valid) {
			// 调用登录接口
			axios.post('/users/login', loginForm)
			.then(res => {
				console.log(res.data)
				if (!(res.data.code == 0)){
					ElMessage.error('登录失败，请稍后再试')
					throw new Error('登录失败，请稍后再试')
				}
				return res.data
			})
			.then(data => {
				ElMessage.success("登陆成功")
				localStorage.setItem('token', data.data.token)
				router.push("/")
			})
			.catch(() => {
				console.error("登录错误")
				ElMessage.error('登录错误，请稍后再试')
			})
		} else {
			console.log('用户名或密码不符合规则')
			return false
		}
	})
}

const resetForm = () => {
	(loginFormRef.value as any).resetFields()
}
</script>


<style scoped>
.login-container {
	display: flex;
	justify-content: center;
	align-items: center;
	height: 100vh;
	background-color: #f0f2f5;
}

.box-card {
	width: 480px;
}
</style>